<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\System;
use App\Models\User;
use App\Models\Share;
use App\Models\MealUserCard;
use App\Models\MealOrder;
use App\Services\OSS;

class WeChatController extends Controller
{

  // 微信授权
    public function Authorization(Request $request)
    {
      $params['appid'] = env('CLIENT_WXAPPID');
      $params['secret'] = env('CLIENT_WXSECRET');
      $params['js_code'] = $request->input('code');
      $nickname = $request->input('nickname');
      $avatar = $request->input('avatar');
      $share_userid = $request->input('share_userid',false);
      $params['grant_type'] = 'authorization_code';
      $param_str = http_build_query($params);
      $result = $this->getCurl("https://api.weixin.qq.com/sns/jscode2session?".$param_str);
      $result['code'] = $params['js_code'];
      // dd($result);
      $user = new User;
      $insertData = ['nicename'=>$nickname,'avatar'=>$avatar,'openid'=>$result['openid'],'session_key'=>$result['session_key'],'share_userid'=>$share_userid];
      if(isset($result['unionid'])){
        $insertData['unionid'] = $result['unionid'];
      }
      $res = $user->add($insertData);
      
      return response()->json($res);
    }

    /**
     * 解密用户手机号
     */
    public function dePhone(Request $request)
    {
      require app_path("Common/wxphone/wxBizDataCrypt.php");
      $user = new User;
      $appid = env('CLIENT_WXAPPID');//小程序APPID
      $sessionKey = $request->input('sessionKeyB64');
      $iv = $request->input('ivB64');
      $encryptedData = $request->input('encryptDataB64');
      $userid = $request->input('user_id');

      $pc = new \WXBizDataCrypt($appid, $sessionKey);
      $errCode = $pc->decryptData($encryptedData, $iv, $data);

      $userdata = $user->where('user_id',$userid)->first();
      $userdata->avatar = $request->input('avatar');
      $userdata->nicename = $request->input('nickname');
      $userdata->tel = json_decode($data,true)['phoneNumber'];

      $userdata->save();

      if($errCode == 0){
        return response()->json(['success'=>true,'code'=>'000','message'=>'完成','data'=>[
          'avatar'=>$userdata->avatar,
          'nicename'=>$userdata->nicename,
          'tel'=>$userdata->tel,
          'user_id'=>$userdata->user_id,
          'password'=>$userdata->small_program_session,
          'small_program_code'=>$userdata->small_program_code,
        ]]);
      }else{
        return response()->json(['success'=>false,'code'=>'000','message'=>'解密出错，请稍后再试！']);
      }
    }
  /**
   * 生成二维码
   */
  public function test(Request $request)
  {
    $system = new System;
    $token = $system->get('pro_access_token')['data']['value'];
    $res = curl_post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$token,json_encode([
          'scene'=>$request->input('user_id'),
        ]));
    
    header('Content-type:image/jpeg');
    echo ($res);
  }

  /**
   * 生成二维码
   */
  public function qrcode(Request $request)
  {
    $system = new System;
    $user = new User;
    $info = $user->where('user_id',$request->input('user_id'))->first();
    // $savefile = merge_img(base_path('resources/tmp/').'tmp.jpeg',base_path().'/public/img/share_b.jpg',$info);
    // dd($savefile);
    // die;
    if($info->qrcode && count(explode(',',$info->qrcode)) == 3){
      $filenames = explode(',',$info->qrcode);
      $filename3 =  $filenames[0];
      $filename =  $filenames[1];
      $filename2 =  $filenames[2];
    }else{
      $token = $system->get('pro_access_token')['data']['value'];
      $res = curl_post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$token,json_encode([
            'scene'=>$request->input('user_id'),
          ]));
      $filename_tmp = md5(uniqid(microtime(true),true));
      file_put_contents(base_path('resources/tmp/').$filename_tmp.'.jpeg', $res);
      // 第一背景图
      $savefile3 = merge_img(base_path('resources/tmp/').$filename_tmp.'.jpeg',base_path().'/public/img/share_c.jpg',$info);
      $filename3 = '/'.date('Ymd').'/'.md5(uniqid(microtime(true),true)).'.jpeg';
      OSS::publicUpload(config('aliyun.BucketName'),'Wechat/'.$filename3,$savefile3);
      unlink($savefile3);
      // 第二背景图
      $savefile = merge_img(base_path('resources/tmp/').$filename_tmp.'.jpeg',base_path().'/public/img/share_b.jpg',$info);
      $filename = '/'.date('Ymd').'/'.md5(uniqid(microtime(true),true)).'.jpeg';
      OSS::publicUpload(config('aliyun.BucketName'),'Wechat/'.$filename,$savefile);
      unlink($savefile);
      // 第三背景图
      $savefile2 = merge_img(base_path('resources/tmp/').$filename_tmp.'.jpeg',base_path().'/public/img/share_a.jpg',$info);
      $filename2 = '/'.date('Ymd').'/'.md5(uniqid(microtime(true),true)).'.jpeg';
      OSS::publicUpload(config('aliyun.BucketName'),'Wechat/'.$filename2,$savefile2);
      unlink($savefile2);
      unlink(base_path('resources/tmp/').$filename_tmp.'.jpeg');
      $info->qrcode = $filename3.','.$filename.','.$filename2;
      $info->save();
    }
    $url = 'https://jiashilexiang.oss-cn-beijing.aliyuncs.com/Wechat/';
    return response()->json([
      'success'=>true,
      'code'=>'000',
      'message'=>'上传成功',
      'filename'=>[$url.$filename3,$url.$filename,$url.$filename2]
    ]);
  }

    public function getResult(Request $request)
	  {
  		/*$echoStr = $request->input('echostr');
  		$signature = $request->input('signature');
          $timestamp = $request->input('timestamp');
          $nonce = $request->input('nonce');
                   
          $token = env("WXGZH_TOKEN");
          $tmpArr = array($token, $timestamp, $nonce);
          // use SORT_STRING rule
          sort($tmpArr, SORT_STRING);
          $tmpStr = implode( $tmpArr );
          $tmpStr = sha1( $tmpStr );
           
          if( $tmpStr == $signature ){
              echo $echoStr;
              die;
          }else{
              echo "err";
  	    	die;
          }*/
  	    $postStr = file_get_contents('php://input');
  	    //extract post data
  	    if (empty($postStr)){
  	    	echo "err";
  	    	die;
  	    }
          /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
             the best way is to check the validity of xml by yourself */
          libxml_disable_entity_loader(true);
          //把XML数据转换为$postObj对象
          $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
          //获取接收到的数据信息
          $fromUsername = $postObj->FromUserName;
          $toUsername = $postObj->ToUserName;
          //获取MsgType属性
          $msgType = $postObj->MsgType; // 严格区分大小写的
          //获取语音识别后的结果
          $rec = $postObj->Recognition;
          $keyword = trim($postObj->Content);
          $time = time();
          //文本回复接口的模板
          $textTpl = "<xml>
                      <ToUserName><![CDATA[%s]]></ToUserName>
                      <FromUserName><![CDATA[%s]]></FromUserName>
                      <CreateTime>%s</CreateTime>
                      <MsgType><![CDATA[%s]]></MsgType>
                      <Content><![CDATA[%s]]></Content>
                      </xml>";
          //音乐消息回复接口模板
          $musicTpl = "<xml>
                       <ToUserName><![CDATA[%s]]></ToUserName>
                       <FromUserName><![CDATA[%s]]></FromUserName>
                       <CreateTime>%s</CreateTime>
                       <MsgType><![CDATA[%s]]></MsgType>
                       <Music>
                        <Title><![CDATA[%s]]></Title>
                        <Description><![CDATA[%s]]></Description>
                        <MusicUrl><![CDATA[%s]]></MusicUrl>
                        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                       </Music>
                       </xml>";
          //图文消息回复接口模板
          $newsTpl = "<xml>
                      <ToUserName><![CDATA[%s]]></ToUserName>
                      <FromUserName><![CDATA[%s]]></FromUserName>
                      <CreateTime>%s</CreateTime>
                      <MsgType><![CDATA[%s]]></MsgType>
                      <ArticleCount>%s</ArticleCount>
                      <Articles>
                      <item>
                          <Title><![CDATA[%s]]></Title>
                          <Description><![CDATA[%s]]></Description>
                          <PicUrl><![CDATA[%s]]></PicUrl>
                          <Url><![CDATA[%s]]></Url>
                      </item>
                      </Articles>
                      </xml>";
          // 纯图片
          $imgTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Image>
                      <MediaId><![CDATA[%s]]></MediaId>
                    </Image>
                  </xml>";
          // 关注/取消关注事件
          $eventTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Event><![CDATA[%s]]></Event>
              </xml>";
          //判断消息的类型text/image/voice消息
          switch($msgType) {
              case 'text': // 被动回复
                  switch ($keyword) {
                    case '118次卡':
                      $msgType = "text";
                      $contentStr = "次卡以上线2"; //回复内容
                      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                      echo $resultStr;
                      break;
                    case '领红包':
                    	$system = new System;
                      $user = new User;
                      $token = $system->get('gzh_access_token','getGzhToken')['data']['value'];
                      $openid = $fromUsername;
                      $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
                      $data = json_decode(curl_get($url),true);
                      $user->where('unionid',$data['unionid'])->update(['reopenid'=>$openid]);
                      $res = $this->gzhSendRedBapk($openid);
                      if(!$res['success']){
                        $msgType = "text";
                        $contentStr = "没有可领取红包，<a data-miniprogram-appid='wx0a68cca25ebaf9b4' data-miniprogram-path='pages/index/index' href='https://jiashilexiang.cn'>分享身边人购卡</a>享优惠，你得现金红包[红包]"; //回复内容
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                      }else{
                        $msgType = "text";
                        $contentStr = "恭喜获得分享红包\n<a data-miniprogram-appid='wx0a68cca25ebaf9b4' data-miniprogram-path='pages/index/index' href='https://jiashilexiang.cn'>分享有红包，红包无限领</a>"; //回复内容0
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                      }
                    	break;
                  }
              break;
              case 'image':
                  $msgType = "text";
                  $contentStr = "您发送的是图片消息！"; //回复内容
                  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                  echo $resultStr;
              break;
              case 'voice':
                  $msgType = "text";
                  $contentStr = "您发送的是语音消息，内容为：".$rec; //回复内容
                  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                  echo $resultStr;
              break;
              case "event":// 事件
                  // $testlog = new TestLog;
                  switch ($postObj->Event) {
                    case 'subscribe': // 订阅关注公众号
                      // $system = new System;
                      // $user = new User;
                      // $token = $system->get('gzh_access_token','getGzhToken')['data']['value'];
                      // $openid = $fromUsername;
                      // $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
                      /*if($logs){
                        $msgType = "image";
                        echo sprintf($imgTpl, $fromUsername, $toUsername, $time, $msgType, $logs->merge_img);
                      }*/
                      // file_put_contents(base_path('resources/tmp/').'log.txt', curl_get($url));
                      // $data = json_decode(curl_get($url),true);
                      // $user->where('unionid',$data['unionid'])->update(['reopenid'=>$openid]);
                      // $this->gzhSendRedBapk($openid);
                      $contentStr = "欢迎关注嘉时乐享，在这里你将会对午餐有全新的体验~\n\n同时使用嘉时乐享小程序，购买套餐饭卡，福利不断！\n\n我们有 【39.9体验卡】【99套餐卡】【198餐卡】【258次卡】<a data-miniprogram-appid='wx0a68cca25ebaf9b4' data-miniprogram-path='pages/myCard/myCard' href='https://jiashilexiang.cn'>打开小程序</a>可查看具体餐卡介绍呦~";
                        echo sprintf($textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
                      break;
                    case 'SCAN': // 扫码
                      $system = new System;
                      $user = new User;
                      $token = $system->get('gzh_access_token','getGzhToken')['data']['value'];
                      $openid = $fromUsername;
                      $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$fromUsername}&lang=zh_CN";
                      /*if($logs){
                        $msgType = "image";
                        echo sprintf($imgTpl, $fromUsername, $toUsername, $time, $msgType, $logs->merge_img);
                      }*/
                      // file_put_contents(base_path('resources/tmp/').'log.txt', curl_get($url));
                      $data = json_decode(curl_get($url),true);
                      $user->where('unionid',$data['unionid'])->update(['reopenid'=>$fromUsername]);
                      $this->gzhSendRedBapk($fromUsername);
                      break;
                    case 'CLICK': // 菜单点击
                      if($postObj->EventKey == 'hongbao'){
                        $system = new System;
                        $user = new User;
                        $token = $system->get('gzh_access_token','getGzhToken')['data']['value'];
                        $openid = $fromUsername;
                        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
                        $data = json_decode(curl_get($url),true);
                        $user->where('unionid',$data['unionid'])->update(['reopenid'=>$openid]);
                        $res = $this->gzhSendRedBapk($openid);
                        if(!$res['success']){
                          $msgType = "text";
                          $contentStr = "没有可领取红包，<a data-miniprogram-appid='wx0a68cca25ebaf9b4' data-miniprogram-path='pages/index/index' href='https://jiashilexiang.cn'>分享身边人购卡</a>享优惠，你得现金红包[红包]"; //回复内容
                          $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                          echo $resultStr;
                        }else{
                          $msgType = "text";
                          // $contentStr = $res['data'][1]['err_code_des']; //回复内容0
                          $contentStr = "<a data-miniprogram-appid='wx0a68cca25ebaf9b4' data-miniprogram-path='pages/index/index' href='https://jiashilexiang.cn'>分享有红包，红包无限领</a>"; //回复内容0
                          $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                          echo $resultStr;
                        }
                      }
                      break;
                    
                    default:
                      # code...
                      break;
                  }
              break;
          }
  	}


	 /**
	  * 发送红包
	  */
    public function sendRedBapk($openid,$money=1)
    {
    	$share = new Share;
      $user = new User;
    	$system = new System;
      $userInfo = $user->where('small_program_code',$openid)->orWhere('reopenid',$openid)->orWhere('user_id',$openid)->first();
    	// $userInfo = $user->where('reopenid',$openid)->first();
    	$shareInfo = $share->where([['user_id','=',$userInfo->user_id],['status','=',0]])->first();
    	if(!$shareInfo){
    		return response()->json([
    			'success'=>false,
    			'code'=>'004',
    			'message'=>'您的账号中没有可领取红包'
    		]);
    	}
      $jine = $system->where('option','wx_share_quota')->first();
      if($shareInfo->toorme==1){
        $money = explode('|',$jine->value)[0];
      }else{
        $money = explode('|',$jine->value)[1];
      }
      if($money==0){
        $shareInfo->status = 1;
        $shareInfo->save();
        return response()->json(['success'=>true,'code'=>'000','message'=>'发送成功！']);
      }
    	$data = [
    		// 随机字符串
    		"nonce_str"=>strtoupper($this->createNonceStr(32)),
    		// 自定义商户订单号
    		"mch_billno"=>$shareInfo->share_billno,
    		// 商户号
    		"mch_id"=>"1510278791",
    		// 公众账号appid
        // "wxappid"=>env("GZHWXAPPID"),
    		"wxappid"=>env("CLIENT_WXAPPID"),
    		// 商户名称
    		"send_name"=>"嘉时乐享",
    		// 用户openid
    		"re_openid"=>$userInfo->small_program_code,
    		// 付款金额
    		"total_amount"=>($money*100),
    		// 红包发放总人数
    		"total_num"=>1,
    		// 红包祝福语
    		"wishing"=>"感谢参与嘉时乐享分享领现金活动",
    		// Ip地址
    		// "client_ip"=>$_SERVER['SERVER_ADDR'],
    		// 活动名称
    		"act_name"=>"分享领红包",
    		// 备注	
    		"remark"=>"分享不限次数，分享越多赚的越多",
    		// 场景id
    		"scene_id"=>"PRODUCT_1",
        // 小程序
        "notify_way" => "MINI_PROGRAM_JSAPI",
    	];
    	$data['sign'] = strtoupper($this->setSign($data,env('WXAPI_KEY')));
    	$filenameCert = base_path().'/resources/cert/apiclient_cert.pem';
	    $filenameKey = base_path().'/resources/cert/apiclient_key.pem';
	    // file_put_contents($filenameCert,file_get_contents($merchantInfo->apiclient_cert));
	    // file_put_contents($filenameKey,file_get_contents($merchantInfo->apiclient_key));
    	// $res = $this->payPostData("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack",$this->arrayToXml($data),$filenameCert,$filenameKey);
      $res = $this->payPostData("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendminiprogramhb",$this->arrayToXml($data),$filenameCert,$filenameKey);
      $resData = xml_to_array($res);
      // return response()->json(['success'=>true,'code'=>'000','message'=>'发送成功！','data'=>[$res,$resData]]);
      if($resData['result_code'] == 'SUCCESS'){
        $shareInfo->status = 1;
        $shareInfo->package_sign = $resData['package'];
        $shareInfo->save();
        return response()->json(['success'=>true,'code'=>'000','message'=>'发送成功！','data'=>[$res,$resData]]);
      }else{
        return response()->json(['success'=>true,'code'=>'000','message'=>'发送失败！','data'=>[$res,$resData]]);
      }
    }

    /**
    * 公众号发送红包
    */
    public function gzhSendRedBapk($openid,$money=1)
    {
      $share = new Share;
      $user = new User;
      $system = new System;
      $userInfo = $user->where('reopenid',$openid)->first();
      $shareInfo = $share->where([['user_id','=',$userInfo->user_id],['status','=',0]])->orWhere(function($q)use($userInfo){
        return $q->where([['user_id','=',$userInfo->user_id],['status','=',1]])->whereNotNull('package_sign');
      })->first();
      if(!$shareInfo){
        return [
          'success'=>false,
          'code'=>'004',
          'message'=>'您的账号中没有可领取红包'
        ];
      }
      $jine = $system->where('option','wx_share_quota')->first();
      if($shareInfo->toorme==1){
        $money = explode('|',$jine->value)[0];
      }else{
        $money = explode('|',$jine->value)[1];
      }
      if($money==0){
        $shareInfo->status = 2;
        $shareInfo->save();
        return ['success'=>true,'code'=>'000','message'=>'发送成功！'];
      }
      $data = [
        // 随机字符串
        "nonce_str"=>strtoupper($this->createNonceStr(32)),
        // 自定义商户订单号
        "mch_billno"=>$shareInfo->share_billno,
        // 商户号
        "mch_id"=>"1510278791",
        // 公众账号appid
        "wxappid"=>env("GZHWXAPPID"),
        // 商户名称
        "send_name"=>"嘉时乐享",
        // 用户openid
        "re_openid"=>$userInfo->reopenid,
        // 付款金额
        "total_amount"=>($money*100),
        // 红包发放总人数
        "total_num"=>1,
        // 红包祝福语
        "wishing"=>"感谢参与嘉时乐享分享领现金活动",
        // Ip地址
        "client_ip"=>$_SERVER['SERVER_ADDR'],
        // 活动名称
        "act_name"=>"分享领红包",
        // 备注 
        "remark"=>"分享不限次数，分享越多赚的越多",
        // 场景id
        "scene_id"=>"PRODUCT_1",
      ];
      $data['sign'] = strtoupper($this->setSign($data,env('WXAPI_KEY')));
      $filenameCert = base_path().'/resources/cert/apiclient_cert.pem';
      $filenameKey = base_path().'/resources/cert/apiclient_key.pem';
      // file_put_contents($filenameCert,file_get_contents($merchantInfo->apiclient_cert));
      file_put_contents(base_path('storage/logs/').'wxpay.log',json_encode($data),FILE_APPEND);
      $res = $this->payPostData("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack",$this->arrayToXml($data),$filenameCert,$filenameKey);
      $resData = xml_to_array($res);
      $shareInfo->status = 2;
      $shareInfo->save();
      return ['success'=>true,'code'=>'000','message'=>'发送成功！','data'=>[$res,$resData]];
    }

    /**
     * 
     */
    private function xmltoarr($xml)
    {
        //xml字符串转数组
        $objectxml = simplexml_load_string($xml);//将文件转换成 对象
        $xmljson= json_encode($objectxml );//将对象转换个JSON
        return $xmljson;
        $xmlarray=json_decode($xmljson,true);//将json转换成数组
        return $xmlarray;
    }

    /**
     * 签名
     */
    public function setSign($params,$apikey)
    {
    	ksort($params);
    	// $params = urldecode(http_build_query($params)."&key=".env("WECHAT_OFFICIAL_ACCOUNT_API_KEY"));
    	$params = urldecode(http_build_query($params)."&key=".$apikey);
    	return md5($params);
    }

    public function arrayToXml($arr) {
	    $xml = "<xml>";
	    foreach ($arr as $key => $val){
	        if (is_numeric($val)){
	            $xml.="<$key>$val</$key>";
	        }
	        else
	            $xml.="<$key><![CDATA[$val]]></$key>";
	    }
	    $xml.="</xml>";
	    return $xml;
	  }

    //获取随机字符串
  	private function createNonceStr($length = 16) {
  		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  		$str = "";
  		for ($i = 0; $i < $length; $i++) {
  		 $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  		}
  		return $str;
  	}

    public function payPostData($url,$postfields,$certSrc,$keySrc)
    {
  	    $ch = curl_init();
  	    $params[CURLOPT_URL] = $url;    //请求url地址
  	    $params[CURLOPT_HEADER] = false; //是否返回响应头信息
  	    $params[CURLOPT_RETURNTRANSFER] = 1; //是否将结果返回
  	    $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
  	    $params[CURLOPT_POST] = 1;
  	    $params[CURLOPT_POSTFIELDS] = $postfields;
  	    $params[CURLOPT_SSL_VERIFYPEER] = false;
  	    $params[CURLOPT_SSL_VERIFYHOST] = false;
  	    //以下是证书相关代码
  	    $params[CURLOPT_SSLCERTTYPE] = 'PEM';
  	    // $params[CURLOPT_SSLCERT] = base_path().'/resources/apiclient_cert.pem';
  	    $params[CURLOPT_SSLCERT] = $certSrc;
  	    $params[CURLOPT_SSLKEYTYPE] = 'PEM';
  	    // $params[CURLOPT_SSLKEY] = base_path().'/resources/apiclient_key.pem';
  	    $params[CURLOPT_SSLKEY] = $keySrc;
  	    $params[CURLOPT_HTTPHEADER] = ['Content-Type: text/xml'];
  	    curl_setopt_array($ch, $params); //传入curl参数
  	    $content = curl_exec($ch); //执行
  	    $error = curl_errno($ch);
  	    curl_close($ch); //关闭连接
  	    if($content){
  	    	return $content;
  	    }else{
  	    	return $error;
  	    }
  	}

  	private function getCurl($url,$json=false)
  	{
  	    $ch = curl_init();
  	    curl_setopt($ch, CURLOPT_URL, $url);
  	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
  	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
  	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  	    $output = curl_exec($ch);
  	    curl_close($ch);
  	    if($json){
  	    	return $output;
  	    }else{
  	    	return json_decode($output, true);
  	    }
  	}

  	/**
     * 检测accesstoken是否可用
     */
    public function isAccessToken($accessToken,$openid)
    {
    	$url = 'https://api.weixin.qq.com/sns/auth?access_token='.$accessToken.'&openid='.$openid;
    	$result = $this->getCurl($url);
    	return $result;
    }

    /**
     * 金额修改
     */
    public function editAccount(Request $request)
    {
      $system = new System;
      if($request->input('wx_share_to',false) || $request->input('wx_share_in',false)){
        $e = $system->where('option','wx_share_quota')->value('value');
        $er = explode('|',$e);
        if($request->input('wx_share_to',false) !== false){
          $er[0] = $request->input('wx_share_to',false);
        }
        if($request->input('wx_share_in',false) !== false){
          $er[1] = $request->input('wx_share_in',false);
        }
        return response()->json($system->set('wx_share_quota',implode('|', $er)));
      }else{
        return response()->json(['success'=>true,'code'=>'000','message'=>'成功']);
      }
    }

    /**
     * 用户协议
     */
    public function agreement()
    {
      $content_m = System::where('option','user_agreement')->first();
      return view('user.userxieyi',['content'=>$content_m->content]);
    }

    /**
     * 小程序红包
     */
    // public function test()
    // {
    //   // 执行退款
    //   // require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
    //   // $wx = new \Wxpayandroid;
    //   // $tui = $wx->refund(138,"8901611368361312");
    //   // dd($tui);
    //   $data = MealOrder::where('order_id',10130)->selectRaw('*,null as shop_name,null as delivery_if,null as delivery_info')->first()->toArray();
    //   return response()->json(['message'=>'您有一个新的嘉时订单','status'=>1,'orderid'=>123,'data'=>$data]);
    // }

    /**
     * 领红包
     */
    public function receiveRedPack(Request $request)
    {
      $userid = $request->input('user_id');
      $action = $request->input('action');
      $share = new Share;
      $shareInfo = $share->where([['user_id','=',$userid],['status','=',1]])->first();
      if(!$shareInfo){
        return response()->json([
          'success'=>false,
          'code'=>'004',
          'message'=>'您的账号中没有可领取红包',
          'data'=>[]
        ]);
      }
      // $jine = $system->where('option','wx_share_quota')->first();
      
      if(empty($shareInfo->package_sign)){
        return response()->json([
          'success'=>true,'code'=>'000','message'=>'生成成功！','data'=>[]
        ]);
      }
      $this->sendRedBapk($userid);
      $data = [
        // 时间戳
        "timeStamp"=>time(),
        // 随机字符串
        "nonceStr"=>($this->createNonceStr(32)),
        // 商户号
        "package"=>urlencode($shareInfo->package_sign),
        // 公众账号appid
        "appId"=>env("CLIENT_WXAPPID"),
      ];
      $data['sign'] = $this->setSign($data,env('WXAPI_KEY'));
      $data['signType'] = 'MD5';
      $data['timeStamp'] = (string)$data['timeStamp'];
      if($action=='set'){
        $shareInfo->status = 2;
        $shareInfo->save();
      }
      return response()->json([
        'success'=>true,'code'=>'000','message'=>'生成成功！','data'=>$data
      ]);
    }

    /**
     * 查询带领取红包
     */
    public function lingqupack(Request $request)
    {
      $userid = $request->input('user_id');
      $share = new Share;
      $shareInfo = $share->where([['user_id','=',$userid],['status','=',0],['toorme','=',0]])->first();
      if(!$shareInfo){
        return response()->json([
          'success'=>false,
          'code'=>'004',
          'message'=>'您的账号中没有可领取红包',
          'data'=>[]
        ]);
      }
      // $jine = $system->where('option','wx_share_quota')->first();
      
      /*if(empty($shareInfo->package_sign)){
        return response()->json([
          'success'=>false,'code'=>'004','message'=>'您的账号中没有可领取红包'
        ]);
      }*/

      return response()->json([
          'success'=>true,'code'=>'000','message'=>'您有待领取红包，请及时查收！'
        ]);
    }

    /**
     * 首页
     */
    public function homeData(Request $request)
    {
      $userid = $request->input('user_id');
      $content_m = System::where('option','user_agreement')->first();
      $content = json_decode(file_get_contents(config('app.homejson')."ppt.json"),true);
      $usercard = new MealUserCard;
      $mycard = $usercard
        ->leftJoin('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where([
            ['lexiang_meal_user_card.users_id','=',$userid],
            ['lexiang_meal_user_card.card_invalid','=',1]
        ])
        ->select('lexiang_meal_user_card.*','lexiang_meal_card.card_img','lexiang_meal_card.start_time','lexiang_meal_card.stop_time','lexiang_meal_card.card_name','lexiang_meal_card.card_desc')
        ->first();

      return response()->json([
        'success'=>true,
        'code'=>'000',
        'message'=>'查询完成',
        'data'=>[
          'home_data'=>$content[0],
          'mycard'=>$mycard,
        ]
      ]);
    }
}
